package org.opens.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * excle工具类
 * @author zhangyuming
 *
 */
public class ExcelUtils {
    /**
     * spring的servlet使用的excel导出
     *
     * @param list 数据
     * @param title 标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName 件名称
     * @param isCreateHeader 是否创建表头
     * @param response web响应对象爱能
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据
     * @param title     标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  文件名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }

    /**
     * excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param response web响应对象爱能
     * @param workbook excel数据
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        ServletOutputStream outputStream = null;

        try {
            // 获取输出流
            outputStream = response.getOutputStream();

            // 使axios请求和可以查看到Content-Disposition属性, 不设置这个将无法获取到
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            // 设置编码
            response.setCharacterEncoding("UTF-8");
            // 设置响应类型
            response.setHeader("content-Type", "application/vnd.ms-excel");

            workbook.write(outputStream);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        } finally {
            // 关闭资源
            IoUtil.close(outputStream);
            IoUtil.close(workbook);
        }
    }

    /**
     * excel 导入
     *
     * @param filePath   excel文件路径
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       excel文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        return importExcel(file, titleRows, headerRows, false, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       上传的文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param needVerify 是否检验excel内容
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerify, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerify  是否检验excel内容
     * @param pojoClass   pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }

        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        params.setNeedVerify(needVerify);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * 支持验证的方式进行导入
     * @param inputStream 输入流
     * @param titleRows title的行数
     * @param headerRows header的行数
     * @param pojoClass 对应的实体类
     */
    public static <T> ExcelImportResult<T> importExcelVerify(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (inputStream == null) {
            return null;
        }

        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        params.setNeedVerify(true);

        try {
            return ExcelImportUtil.importExcelMore(inputStream, pojoClass, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(inputStream);
        }
    }

    /**
     * 从web上传文件对象导入
     * @param multipartFile web上传文件对象爱能
     * @param titleRows title行数
     * @param headerRows header行数
     * @param pojoClass 导入实体类信息
     */
    public static <T> ExcelImportResult<T> importExcelVerify(MultipartFile multipartFile, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (multipartFile == null) {
            throw new RuntimeException("导入对象文件不能为空!");
        }

        InputStream inputStream = null;

        try {
            inputStream = multipartFile.getInputStream();
            return importExcelVerify(inputStream, titleRows, headerRows, pojoClass);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 从文件获取输入流后使用完后要关闭.
            IoUtil.close(inputStream);
        }
    }

    /**
     * 从文件导入
     * @param file 文件对象
     * @param titleRows title行数
     * @param headerRows header行数
     * @param pojoClass 实体类信息
     */
    public static <T> ExcelImportResult<T> importExcelVerify(File file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            throw new RuntimeException("导入对象文件不能为空!");
        }

        if (!file.exists()) {
            throw new RuntimeException("导入文件不存在!");
        }

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            return importExcelVerify(fileInputStream, titleRows, headerRows, pojoClass);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(fileInputStream);
        }
    }

    /**
     * 从文件路径导入
     * @param filePath 文件路径
     * @param titleRows title行数
     * @param headerRows header行数
     * @param pojoClass 实体类信息
     */
    public static <T> ExcelImportResult<T> importExcelVerify(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StrUtil.isBlank(filePath)) {
            throw new RuntimeException("导入文件路径不能为空!");
        }

        File file = new File(filePath);

        return importExcelVerify(file, titleRows, headerRows, pojoClass);
    }

    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        /**
         * 文件类型
         */
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
